package br.com.android.watcher;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemLongClickListener;

public class Watcher extends Activity implements OnItemLongClickListener{
	private static final int EDIT_ACTION = 1;
	Model m;
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        	//Log.v("Watcher Act", "On create...");
        setContentView(R.layout.main);
        this.m = new Model(this);
        ListView watchlist = (ListView) findViewById(R.id.watchlist);
        watchlist.setOnItemLongClickListener(this);
    	//Log.v("Watcher Act", "Loading ListAdapter from file");
        watchlist.setAdapter(this.m.getAdapter());
        	//Log.v("Watcher Act", "Loading from the file... OK");          
    }
	@Override
	public void onPause(){
		this.m.dismiss();
		super.onStop();
	}
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    		//Log.v("Watcher Act", "Inflating the Menu");
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId() == R.id.itemAdd){
				//Log.v("Watcher Act"," Item do Menu ADD pressionado");
			Intent inputAct = new Intent(this, CharacterInputActivity.class);
				//Log.v("Watcher Act","Starting Activity Input for Result");
			startActivityForResult(inputAct, EDIT_ACTION); 
		}
		if(item.getItemId() == R.id.itemUpdate){
				//Log.v("Watcher Act", "Updating Score...");
			this.m.updateAllScores();
	        	//Log.v("Watcher Act", "Updating Score... OK");
		}
		return true;
	}
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
			//Log.v("Watcher Act","OnActivity Result:");
        switch (requestCode) {
            case EDIT_ACTION:
                try {
                    String name = data.getStringExtra("name");
                    String realm = data.getStringExtra("realm");
                    if (name != null && name.length() > 0 && realm != null && realm.length() > 0) {
                    	//Log.v("Watcher Act","Adding Watch to " + name + "/" + realm);
                    	this.m.addWatch(name, realm);
                    }
                } catch (Exception e) {
                }
                break;
            default:
                break;
        }
    }
	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		//Log.v("Watcher Act","Removendo item # " + arg2);
		m.removeWatch(arg2);
		return true;
	}
}